<template>
  <div class="wiki-list">
    <template v-if="showPage">
      <template v-if="notMember">
        <a-card :bordered="false" style="margin: 0 20px">
          <div class="flex flex-col align-center py-30">
            <WarningFilled style="color: #faad14; font-size: 64px" />
            <div class="mt-20 fs-24">此能力仅团队成员可用</div>
            <div class="mt-10 text-gray-6">当前身份：个人</div>
            <a-row class="mt-20 flex justify-center">
              <a-button
                type="primary"
                style="border-radius: 6px"
                @click="changeTeamPopoverVisible(true)"
              >
                <template #icon><SwapOutlined /></template>
                切换团队
              </a-button>
              <a-button
                type="primary"
                class="ml-20"
                style="border-radius: 6px"
                @click="addTeamVisible = true"
              >
                <template #icon><PlusCircleOutlined /></template>
                创建团队
              </a-button>
            </a-row>
          </div>
        </a-card>
      </template>
      <template v-else>
        <div class="content">
          <div class="left">
            <div
              style="
                display: flex;
                justify-content: space-between;
                align-items: center;
              "
            >
              <div>企业知识库</div>
              <a-button
                type="link"
                style="padding: 0; margin: 0"
                @click="editCate"
              >
                <template #icon><PlusOutlined /></template>
                添加知识库
              </a-button>
            </div>
            <div class="cate-list beauty-scroller-bar">
              <template v-if="cateList.length > 0">
                <div
                  class="cate-list-item"
                  v-for="(item, index) of cateList"
                  :key="index"
                  @click="onCateClick(item)"
                  :class="
                    currentCate.id == item.id ? 'cate-list-item-current' : ''
                  "
                >
                  <span>{{ item.name }}</span>
                  <a-dropdown :trigger="['click']" v-if="!item.is_root">
                    <span
                      class="ant-dropdown-link"
                      @click.stop
                      style="padding: 0 5px"
                    >
                      <MoreOutlined />
                    </span>
                    <template #overlay>
                      <a-menu>
                        <a-menu-item key="0">
                          <a-button
                            type="link"
                            style="
                              width: 100%;
                              text-align: center;
                              padding: 0 16px;
                              margin: 0;
                            "
                            @click="editCate(item)"
                            >编辑知识库</a-button
                          >
                        </a-menu-item>
                        <a-menu-item key="1" v-if="cateList.length > 1">
                          <a-button
                            type="link"
                            danger
                            style="
                              width: 100%;
                              text-align: center;
                              padding: 0 16px;
                              margin: 0;
                            "
                            @click="deleteCate(item.id)"
                            >删除知识库</a-button
                          >
                        </a-menu-item>
                      </a-menu>
                    </template>
                  </a-dropdown>
                </div>
              </template>
            </div>
          </div>
          <div class="right beauty-scroller-bar">
            <a-alert type="warning">
              <template #message>
                上传知识库支持手动输入文本、文件上传和问答库上传,上传后需要几秒钟学习时间,刷新后可以查看学习状态。
              </template>
            </a-alert>

            <a-tabs
              type="card"
              v-model:activeKey="currentTab"
              style="margin-top: 20px"
              @change="onTabChange"
            >
              <a-tab-pane
                v-for="item of tabList"
                :key="item.key"
                :tab="item.label"
              ></a-tab-pane>
            </a-tabs>

            <a-row align="middle" justify="space-between">
              <a-col>
                <a-input
                  v-model:value="keywords"
                  placeholder="请输入搜索内容"
                  allowClear
                  style="width: 325px"
                />
                <a-button
                  type="primary"
                  @click="getWikiData(true)"
                  style="margin-left: 20px"
                >
                  查找
                </a-button>
                <a-button style="margin-left: 10px" @click="removeKeywords">
                  清空
                </a-button>
              </a-col>
              <a-col>
                <a-button
                  type="primary"
                  ghost
                  style="margin-right: 10px"
                  @click="getWikiData(true)"
                >
                  <template #icon><SyncOutlined /></template>
                  刷新
                </a-button>
                <template v-if="currentTab == 'text'">
                  <a-button type="primary" @click="modalVisible = 'add'">
                    <PlusOutlined />添加文本
                  </a-button>
                </template>
                <template v-if="currentTab == 'file'">
                  <a-button type="primary" @click="modalVisible = 'splitText'">
                    <UploadOutlined />上传文件
                  </a-button>
                </template>
                <template v-if="currentTab == 'web'">
                  <a-button type="primary" @click="modalVisible = 'webCapture'">
                    <UploadOutlined />网页读取
                  </a-button>
                </template>
                <template v-if="currentTab == 'qa'">
                  <a-button type="primary" @click="modalVisible = 'csvImport'">
                    <UploadOutlined />导入回答
                  </a-button>
                </template>
              </a-col>
            </a-row>
            <div class="table-wrap">
              <a-table
                :columns="columns"
                :data-source="wikiData"
                :loading="tableLoading"
                :pagination="false"
                @change="handleTableChange"
                rowKey="id"
              >
                <template #question="{ text }">
                  <div
                    style="
                      max-height: 200px;
                      overflow: hidden auto;
                      padding-right: 10px;
                    "
                    class="beauty-scroller-bar"
                  >
                    {{ text }}
                  </div>
                </template>
                <template #operation="{ record }">
                  <a-button
                    class="mr-20"
                    type="text"
                    style="background-color: #f7f0ff"
                    @click="onEditClick(record)"
                  >
                    <template #icon>
                      <EditOutlined style="color: rgb(255, 101, 98)" />
                    </template>
                  </a-button>
                  <a-button type="text" @click="onDeleteData(record.id)">
                    <template #icon>
                      <DeleteOutlined style="color: rgb(255, 101, 98)" />
                    </template>
                  </a-button>
                </template>
              </a-table>
            </div>

            <div class="pagination-wrap">
              <a-pagination
                v-model:current="page"
                :total="total"
                @change="onPageChange"
              />
            </div>
          </div>
        </div>
      </template>
    </template>

    <AddTeam
      :visible="addTeamVisible"
      @onClose="addTeamVisible = false"
      @success="addTeamSuccess"
    />

    <LoginModal
      :visible="loginVisible"
      @onClose="loginVisible = false"
      @loginCallback="loginCallback"
    />

    <a-modal
      :visible="editWikiVisible"
      :title="editWikiId ? '编辑知识库' : '新增知识库'"
      centered
      :width="400"
      @cancel="editWikiVisible = false"
      @ok="onSubmitWiki"
      ok-text="保存"
      :zIndex="1002"
    >
      <div class="modal-content">
        <a-form :model="wikiFormRef" layout="vertical">
          <a-form-item label="知识库名称" v-bind="wikiValidateInfos.name">
            <a-input
              v-model:value="wikiFormRef.name"
              placeholder="请填写知识库名称"
            />
          </a-form-item>
          <a-form-item label="对接Token" v-bind="wikiValidateInfos.token">
            <a-input
              v-model:value="wikiFormRef.token"
              placeholder="不填写则自动创建"
            />
          </a-form-item>
        </a-form>
      </div>
    </a-modal>

    <a-modal
      :visible="!!modalVisible"
      :title="modalTitle[modalVisible]"
      @ok="modalHandleOk(modalVisible)"
      @cancel="modalVisible = null"
      width="90%"
      :wrapClassName="
        'wiki-modal-warp' +
        (modalVisible == 'splitText' ? ' split-text-modal' : '')
      "
      :confirm-loading="modalConfirmLoading"
      okText="确认导入"
    >
      <template v-if="modalVisible == 'add' || modalVisible == 'edit'">
        <div class="flex h-full">
          <div class="mr-20 w-full h-full">
            <div class="mb-5">匹配的知识点</div>
            <a-textarea
              v-model:value="question"
              style="height: calc(100% - 30px); resize: none"
              placeholder="可以理解为问题。"
              :maxlength="3000"
            ></a-textarea>
          </div>
          <div class="h-full w-full mb-5">
            <div class="mb-5">补充知识</div>
            <a-textarea
              v-model:value="answer"
              style="height: calc(100% - 30px); resize: none"
              placeholder="可以理解为需要训练的答案。"
              :maxlength="3000"
            ></a-textarea>
          </div>
        </div>
      </template>

      <template v-if="modalVisible == 'csvImport'">
        <div class="flex h-full">
          <div style="flex: 2 0 0px" class="mr-20">
            <div class="fs-12">
              <p class="mb-0">
                接受一个 xlsx  文件，表格头包含 question 和 answer。question
                代表问题，answer 代表答案。
              </p>
              <p>
                导入前会进行去重，如果问题和答案完全相同，则不会被导入，所以最终导入的内容可能会比文件的内容少。但是，对于带有换行的内容，目前无法去重。
              </p>
            </div>
            <!-- <h3>请保证 csv 文件为 utf-8 编码</h3> -->
            <div class="bl-table mt-10">
              <div class="flex bl-table__ll font-bold fs-12">
                <div style="width: 150px" class="bl-table__li">question</div>
                <div style="flex: 1" class="bl-table__li">answer</div>
              </div>
              <div class="flex bl-table__ll fs-12">
                <view style="width: 150px" class="bl-table__li"
                  >如何申明变量？</view
                >
                <view style="flex: 1" class="bl-table__li"
                  >在Python中，可以使用赋值语句来声明变量。例如，将一个整数值赋给变量x可以这样写：x
                  = 42 这样就将整数值42存储在变量x中了。</view
                >
              </div>
              <div class="flex bl-table__ll fs-12">
                <div style="width: 150px" class="bl-table__li">
                  python中的模型、类和函数是什么意思，有什么区别？
                </div>
                <div style="flex: 1" class="bl-table__li">
                  在Python中，模型（Model）、类（Class）和函数（Function）是不同的概念，用于不同的目的。在Python中，模型是解决特定问题的类、函数和变量的集合，类和函数之间的主要区别在于，类是创建对象的蓝图，而函数是执行特定任务的代码块。一个类可以包含多个函数，但一个函数不能包含一个类。模型则是解决特定问题的类、函数和变量的集合。
                </div>
              </div>
            </div>
            <div
              class="mt-10 text-blue cursor-pointer"
              style="text-decoration: underline"
              @click="downloadFile"
            >
              点击下载xlsx模板
            </div>
            <div class="flex align-center mt-10">
              <a-upload
                accept=".xlsx"
                :showUploadList="false"
                :before-upload="importCsvBeforeUpload"
                :action="`${baseUrl}/work_ai/user/team/wiki/data/load_csv`"
                @change="importCsvUploadChange"
                name="file"
                :data="{ user_token: $utils.getToken() }"
              >
                <a-button
                  :loading="importCsvLoading"
                  type="primary"
                  class="mr-20"
                  >选择 xlsx 问答对</a-button
                >
              </a-upload>
              <div>一共 {{ importCsvData.length }} 组数据</div>
            </div>
          </div>
          <div
            style="
              flex: 3 0 0px;
              background-color: rgb(0 0 0 / 4%);
              overflow: auto;
            "
            class="p-5 fs-12 h-full"
          >
            <div v-for="(data, index) in importCsvData" :key="index">
              <div>Q{{ index + 1 }}. {{ data.question }}</div>
              <div>A{{ index + 1 }}.{{ data.answer }}</div>
            </div>
          </div>
        </div>
      </template>

      <template v-if="modalVisible == 'splitText' || modalVisible == 'webCapture'">
        <div class="h-full flex flex-col">
          <div class="fs-12 px-20" v-if="modalVisible == 'splitText'">
            支持 .txt,.docx,.pdf,.md 文件。AI会自动对文本进行 QA2
            拆分，需要较长训练时间。
          </div>
          <div class="fs-12 px-20 mt-10 text-red" v-if="modalVisible == 'splitText'">
            注意文档中不要放入图片，否则可能导致文件上传失败
          </div>
          <div class="mt-20 px-20 flex align-center">
            <div style="width: 80px">分段模式:</div>
            <div class="flex-1">
              <a-radio-group
                name="radioGroup"
                v-model:value="splitTextModel.mode"
              >
                <a-radio value="subsection">直接分段</a-radio>
                <a-radio value="qa">QA拆分</a-radio>
              </a-radio-group>
            </div>
          </div>
          <div
            class="flex px-20 mt-20 align-center"
            v-if="splitTextModel.mode == 'subsection'"
          >
            <div style="width: 80px">段落长度</div>
            <div class="flex-1">
              <a-slider
                :marks="{
                  300: '300',
                  1000: '1000',
                }"
                :step="50"
                :min="300"
                :max="1000"
                v-model:value="splitTextModel.maxLen"
                :tooltip-visible="true"
                style="width: 300px"
              >
              </a-slider>
            </div>
          </div>
          <div
            class="flex px-20 mt-20 align-center"
            v-if="splitTextModel.mode == 'qa'"
          >
            <div style="width: 80px">下面是</div>
            <div class="flex-1">
              <a-input
                placeholder="搜索相关问题和答案，回车确认"
                v-model:value="splitTextModel.prompt"
              ></a-input>
            </div>
          </div>
          <div class="px-20 mt-20" v-if="modalVisible == 'webCapture'">
            <a-button type="link" style="padding: 0px;border-bottom: 1px solid rgb(255, 101, 98);" @click="webCaptureVisible = true">点击读取网页</a-button>
          </div>
          <div
            class="mt-20 px-20 pr-30"
            style="flex: 1 0 0px; height: 0px; overflow-y: auto"
          >
            <div
              class="mb-30"
              v-for="(chunk, index) in splitTextModel.chunks"
              :key="index"
            >
              <div>文本{{ index + 1 }}</div>
              <div class="mt-5">
                <a-textarea
                  v-model:value="splitTextModel.chunks[index].text"
                  style="height: 155px"
                  rows="10"
                  :placeholder="modalVisible == 'splitText' ? '您可以手动输入，也可以上传文件。文件内容将会解析在此。空内容会自动忽略。' : '您可以手动输入，也可以网页读取。网页内容将会解析在此。空内容会自动忽略。'"
                ></a-textarea>
              </div>
            </div>
          </div>
        </div>
      </template>
      <template #footer v-if="modalVisible == 'splitText'">
        <div class="flex justify-between">
          <div>
            <a-upload
              accept=".txt,.docx,.pdf,.md"
              :showUploadList="false"
              :action="`${baseUrl}/work_ai/user/team/wiki/data/split_load_file`"
              @change="splitTextUploadChange"
              name="file"
              :data="{ user_token: $utils.getToken() }"
              v-if="modalVisible == 'splitText'"
            >
              <a-button :loading="splitTextLoading" type="primary" class="mr-20"
                >选择文件</a-button
              >
            </a-upload>
          </div>
          <div>
            <a-button @click="modalVisible = null">取消</a-button>
            <a-button
              :loading="modalConfirmLoading"
              type="primary"
              @click="modalHandleOk(modalVisible)"
              >确认导入</a-button
            >
          </div>
        </div>
      </template>
    </a-modal>
    <a-modal v-model:visible="webCaptureVisible" @ok="onWebCaptureConfirm" :confirmLoading="webCaptureConfirmLoading">
      <template #title>
        <div>
          <div>链接读取</div>
          <div style="font-size: 12px; color: #a6a6a6; font-weight: normal;">目前仅支持读取静态链接，请注意检查结果</div>
        </div>
      </template>
      <a-textarea v-model:value="webCaptureLink" :rows="12" placeholder="最多10个链接，每行一个。" style="white-space: nowrap;"></a-textarea>
    </a-modal>
  </div>
</template>

<script>
import {
  defineComponent,
  reactive,
  toRefs,
  computed,
  watch,
  toRaw,
  h,
  onBeforeUnmount,
  createVNode,
  inject,
  ref,
} from "vue";
import request from "../../common/utils/request";
import store from "../../store/index";
import { useRoute, useRouter } from "vue-router";
import utils from "../../common/utils/utils";
import { Form, Modal, notification, message } from "ant-design-vue";
import {
  WarningFilled,
  PlusCircleOutlined,
  SwapOutlined,
  PlusOutlined,
  ExclamationCircleOutlined,
  MoreOutlined,
  SyncOutlined,
  DeleteOutlined,
  EditOutlined,
  QuestionCircleOutlined,
  UploadOutlined,
} from "@ant-design/icons-vue";
import AddTeam from "@/components/AddTeam/index.vue";
import apiRequest from "@/common/utils/request";
import defaultSetting from "@/common/utils/defaultSetting";
import { errorHandler } from "@/common/utils/request";

const useForm = Form.useForm;
export default defineComponent({
  name: "Create",
  components: {
    WarningFilled,
    PlusCircleOutlined,
    SwapOutlined,
    PlusOutlined,
    // SettingOutlined,
    AddTeam,
    MoreOutlined,
    SyncOutlined,
    DeleteOutlined,
    EditOutlined,
    UploadOutlined,
  },

  setup() {
    const route = useRoute();
    const router = useRouter();
    const changeTeamPopoverVisible = inject(["changeTeamPopoverVisible"]);
    let baseUrl = defaultSetting.requestDomain;
    if (process.env.NODE_ENV === "development") {
      baseUrl = baseUrl + "/api";
    }

    const state = reactive({
      loginVisible: false,
      showPage: false,
      addTeamVisible: false,
      notMember: false,

      total: 0,
      page: 1,
      pageSize: 20,

      editWikiVisible: false,
      editWikiName: "",
      editWikiId: null,

      wikiSettingVisible: false,

      cateList: [],
      currentCate: {},
      currentTab: 0,
      tabList: [
        {
          key: 0,
          label: "所有",
        },
        {
          key: "text",
          label: "文本",
        },
        {
          key: "file",
          label: "文件",
        },
        {
          key: "web",
          label: "网页",
        },
        {
          key: "qa",
          label: "问答库",
        },
      ],

      wikiData: [],
      keywords: "",
      tableLoading: false,
      question: "",
      answer: "",
      modalConfirmLoading: false,
      editDataId: 0,
      importCsvLoading: false,
      uploadCsvFile: null,
      importCsvData: [],
      visible: false,
      splitTextLoading: false,
    });

    const wikiFormRef = reactive({
      name: "",
      token: "",
    });

    const wikiRulesRef = reactive({
      name: [{ required: true, message: "知识库名称不能为空" }],
    });

    const {
      resetFields: wikiResetFields,
      validate: vikiVilidate,
      validateInfos: wikiValidateInfos,
    } = useForm(wikiFormRef, wikiRulesRef);

    watch(
      () => state.editWikiVisible,
      (val) => {
        if (!val) {
          wikiResetFields();
        }
      }
    );

    const handleTableChange = (pager, filters, sorter) => {
      state.page = pager.current;
      state.pageSize = pager.pageSize;
      getCateList();
    };

    const init = () => {
      state.page = 1;
      state.pageSize = 20;
      state.total = 0;
      state.wikiData = [];
      if (store.state.user.teamId) {
        state.notMember = false;
        getCateList();
      } else {
        state.notMember = true;
      }
    };

    utils.checkLogin().then((isLogin) => {
      if (!isLogin) {
        state.loginVisible = true;
        return;
      }
      state.showPage = true;
      init();
    });

    const loginCallback = () => {
      state.loginVisible = false;
      router.go(0);
    };

    const addTeamSuccess = () => {
      state.addTeamVisible = false;
      init();
    };

    const editCate = (record) => {
      state.editWikiId = null;
      wikiFormRef.name = "";
      wikiFormRef.token = "";

      if (record && record.id) {
        state.editWikiId = record.id;

        wikiFormRef.name = record.name;
        wikiFormRef.token = record.token;
      }
      state.editWikiVisible = true;
    };

    const onSubmitWiki = () => {
      if (vikiVilidate()) {
        if (!wikiFormRef.name) {
          message.error("知识库名称不能为空");
          return;
        }

        let requestType = "post";
        let url = "/user/team/wiki";
        let params = {
          name: wikiFormRef.name,
          token: wikiFormRef.token,
          team_id: store.state.user.teamId,
        };
        if (state.editWikiId) {
          requestType = "put";
          url = "/user/team/wiki";
          params.id = state.editWikiId;
        }
        request[requestType]("/work_ai", url, {
          ...params,
        }).then((res) => {
          message.success("保存成功");
          state.editWikiVisible = false;
          getCateList();
        });
      }
    };

    // 删除
    const deleteCate = (id) => {
      Modal.confirm({
        title: () => `确定要删除吗？`,
        icon: () => createVNode(ExclamationCircleOutlined),
        centered: true,
        onOk() {
          request
            .del("/work_ai", "/user/team/wiki", {
              id,
            })
            .then((res) => {
              message.success("删除成功");
              getCateList();
            });
        },
      });
    };

    const showWikiSetting = () => {
      getSettingDetail();
      state.wikiSettingVisible = true;
    };

    const settingFormRef = reactive({
      name: "",
      intro: "",
      avatar: "",
      token: "",
      use_wiki: 0,
      wiki_search_mode: 1,
      system_prompt: "",
      total_numbers: 0,
      total_art_numbers: 0,
    });

    const settingRulesRef = reactive({
      name: [{ required: true, message: "团队名称不能为空" }],
    });

    const { resetFields, validate, validateInfos } = useForm(
      settingFormRef,
      settingRulesRef
    );

    const settingValidateInfos = validateInfos;

    const getSettingDetail = () => {
      request
        .get("/work_ai", "/user/team", {
          id: store.state.user.teamId,
        })
        .then((res) => {
          if (res.detail) {
            for (let key in settingFormRef) {
              settingFormRef[key] = res.detail[key];
            }
          }
        });
    };

    const onSettingSubmit = () => {
      validate().then(() => {
        let params = {
          id: store.state.user.teamId,
        };
        for (let key in settingFormRef) {
          params[key] = settingFormRef[key];
        }
        request
          .put("/work_ai", "/user/team", {
            ...params,
          })
          .then((res) => {
            message.success("保存成功");
            state.wikiSettingVisible = false;
          });
      });
    };

    watch(
      () => store.state.user.teamId,
      (val) => {
        init();
      }
    );

    const getCateList = () => {
      request
        .get("/work_ai", "/user/team/wiki", {
          page: 1,
          pageSize: 9999,
          team_id: store.state.user.teamId,
        })
        .then((res) => {
          state.cateList = res.list;
          if (res.list.length > 0) {
            state.currentCate = res.list[0];
            getWikiData(true);
          }
        });
    };

    const onCateClick = (item) => {
      if (state.currentCate.id == item.id) {
        return;
      }
      state.currentCate = item;
      getWikiData(true);
    };

    const getWikiData = (init) => {
      state.tableLoading = true;
      if (init) {
        state.page = 1;
      }
      let params = {
        page: state.page,
        pageSize: state.pageSize,
        wiki_id: state.currentCate.id,
      };
      if (state.keywords) {
        params.keywords = state.keywords;
      }
      if (state.currentTab) {
        params.type = state.currentTab;
      }
      request.get("/work_ai", "/user/team/wiki/data", params).then((res) => {
        state.wikiData = res.list;
        state.total = res.total;
        state.tableLoading = false;
      });
    };

    const columns = [
      {
        title: "名称",
        dataIndex: "question",
        key: "question",
        slots: { customRender: "question" },
        align: "center",
      },
      {
        title: "类型",
        dataIndex: "type_txt",
        key: "type_txt",
        width: 200,
        align: "center",
      },
      {
        title: "学习状态",
        dataIndex: "status_text",
        key: "status_text",
        width: 200,
        align: "center",
      },
      {
        title: "修改时间",
        dataIndex: "updated_at",
        key: "updated_at",
        width: 240,
        align: "center",
      },
      {
        title: "操作",
        dataIndex: "operation",
        slots: { customRender: "operation" },
        width: 200,
        align: "center",
      },
    ];

    const removeKeywords = () => {
      state.keywords = "";
      getWikiData(true);
    };

    // 删除
    const onDeleteData = (id) => {
      Modal.confirm({
        title: () => `确定要删除吗？`,
        icon: () => createVNode(ExclamationCircleOutlined),
        centered: true,
        onOk() {
          request
            .del("/work_ai", "/user/team/wiki/data", {
              id,
            })
            .then((res) => {
              message.success("删除成功");
              getWikiData();
            });
        },
      });
    };

    const onTabChange = (key) => {
      getWikiData(true);
    };

    const modalTitle = {
      add: "手动导入数据",
      edit: "更新数据",
      csvImport: "xlsx 问答对导入",
      splitText: "文件导入",
      webCapture: "网页抓取",
    };

    const modalVisible = ref(null);

    const onEditClick = (record) => {
      state.editDataId = record.id;
      state.question = record.question;
      state.answer = record.answer;

      modalVisible.value = "edit";
    };

    watch(modalVisible, (newVisible, oldVisible) => {
      console.log(newVisible, oldVisible);
      if (newVisible == null && (oldVisible == "add" || oldVisible == "edit")) {
        state.question = "";
        state.answer = "";
      }

      if (newVisible == null && oldVisible == "edit") {
        state.editDataId = 0;
      }

      if (newVisible == null && oldVisible == "csvImport") {
        state.importCsvData = [];
        state.uploadCsvFile = null;
      }

      if (newVisible == null && oldVisible == "splitText") {
        splitTextModel.mode = "subsection";
        splitTextModel.prompt = "";
        splitTextModel.chunks = [
          { type: "text", source: "文本输入", text: "" },
        ];
      }

      if (newVisible) {
        state.visible = false;
      }
    });

    const onAddHandle = () => {
      let params = {
        question: state.question,
        answer: state.answer,
        org_id: utils.getOrgId(),
        team_id: store.state.user.teamId,
        wiki_id: state.currentCate.id,
      };

      state.modalConfirmLoading = true;
      apiRequest
        .post("/work_ai", "/user/team/wiki/data", params)
        .then(() => {
          state.modalConfirmLoading = false;
          modalVisible.value = null;

          state.page = 1;
          getWikiData();
        })
        .catch((err) => {
          state.modalConfirmLoading = false;
        });
    };

    const onEditHandle = () => {
      let params = {
        question: state.question,
        answer: state.answer,
        id: state.editDataId,
        wiki_id: state.currentCate.id,
      };

      state.modalConfirmLoading = false;

      apiRequest
        .put("/work_ai", "/user/team/wiki/data", params)
        .then(() => {
          state.modalConfirmLoading = false;
          modalVisible.value = null;

          getWikiData();
        })
        .catch((err) => {
          state.modalConfirmLoading = false;
        });
    };

    const onCsvImportHandle = () => {
      if (!state.uploadCsvFile) {
        return;
      }

      Modal.confirm({
        title: "提示",
        content: "确认导入该数据集?",
        okText: "确认",
        cancelText: "取消",
        onOk() {
          state.modalConfirmLoading = true;

          const data = {
            org_id: utils.getOrgId(),
            team_id: store.state.user.teamId,
            file: state.uploadCsvFile,
            user_token: utils.getToken(),
            wiki_id: state.currentCate.id,
          };

          apiRequest
            .upload("/work_ai", "/user/team/wiki/data/import_csv", data)
            .then(({ data: { count } }) => {
              message.success(
                `导入数据成功，最终导入: ${count} 条数据。需要一段时间训练`
              );

              state.modalConfirmLoading = false;
              modalVisible.value = null;

              state.page = 1;
              getWikiData();
            })
            .catch((err) => {
              state.modalConfirmLoading = false;
            });
        },
      });
    };

    const splitTextModel = reactive({
      mode: "subsection",
      prompt: "",
      chunks: [{type: "text", source: "文本输入", 'text': ''}],
      maxLen: 600,
    });

    const onSplitTextHandle = () => {
      const splitRes = splitTextModel.chunks.filter((item) => item.text);

      if (splitRes.length == 0) {
        return;
      }

      Modal.confirm({
        title: "提示",
        content: `确认导入该文件，需要一定时间进行拆解，该任务无法终止。一共${splitRes.length}组`,
        okText: "确认",
        cancelText: "取消",
        onOk() {
          state.modalConfirmLoading = true;

          const data = {
            org_id: utils.getOrgId(),
            chunks: splitRes,
            team_id: store.state.user.teamId,
            mode: splitTextModel.mode,
            prompt: `下面是"${splitTextModel.prompt || "一段长文本"}"`,
            wiki_id: state.currentCate.id,
            maxLen: splitTextModel.maxLen,
          };

          apiRequest
            .post("/work_ai", "/user/team/wiki/data/split_text", data)
            .then((res) => {
              message.success(`导入数据成功,需要一段拆解和训练`);

              state.modalConfirmLoading = false;
              modalVisible.value = null;

              state.page = 1;
              getWikiData();
            })
            .catch((err) => {
              console.log(err);
              state.modalConfirmLoading = false;
            });
        },
      });
    };

    //下载文件
    const downloadFile = () => {
      const filename = "templates.xlsx";
      const fileUrl = `${baseUrl}/public_web/static/file/org/template.xlsx`;
      const link = document.createElement("a");
      link.style.display = "none";
      link.href = fileUrl;
      link.setAttribute("download", filename);
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    };

    const uploadResponse = (response) => {
      const { code } = response;

      if (code === 1000) {
        return Promise.resolve(response.data);
      } else {
        return errorHandler({ data: response });
      }
    };

    const splitTextUploadChange = ({ file }) => {
      if (file.status === "uploading") {
        state.splitTextLoading = true;
        return;
      }

      if (file.status === "done") {
        state.splitTextLoading = false;

        uploadResponse(file.response).then(({ data }) => {
          splitTextModel.chunks = [data].concat(splitTextModel.chunks);
        });
      }

      if (file.status === "error") {
        state.splitTextLoading = false;
        message.error("上传失败");
      }
    };

    const importCsvBeforeUpload = (file) => {
      state.uploadCsvFile = file;
    };

    const importCsvUploadChange = ({ file }) => {
      if (file.status === "uploading") {
        state.importCsvLoading = true;
        return;
      }

      if (file.status === "done") {
        state.importCsvLoading = false;

        uploadResponse(file.response).then(({ data }) => {
          state.importCsvData = data;
        });
      }

      if (file.status === "error") {
        state.importCsvLoading = false;
        state.uploadCsvFile = null;

        message.error("上传失败");
      }
    };

    const modalHandleOk = (type) => {
      if (type == "add") {
        onAddHandle();
      } else if (type == "edit") {
        onEditHandle();
      } else if (type == "csvImport") {
        onCsvImportHandle();
      } else if (type == "splitText" || type == "webCapture") {
        onSplitTextHandle();
      }
    };

    const onPageChange = (page, pageSize) => {
      state.page = page;
      state.pageSize = pageSize;
      getWikiData();
    };

    const webCaptureVisible = ref(false)
    const webCaptureLink = ref('')
    const webCaptureConfirmLoading = ref(false)
    const onWebCaptureConfirm = () => {
      if (!webCaptureLink.value) {
        return message.error('请输入链接')
      }

      const data = {
        org_id: utils.getOrgId(),
        team_id: store.state.user.teamId,
        links: webCaptureLink.value.split('\n').filter(item => item),
        wiki_id: state.currentCate.id,
      }

      webCaptureConfirmLoading.value = true

      apiRequest
            .post("/work_ai", "/user/team/wiki/data/linkFetch", data)
            .then(({ data }) => {
                splitTextModel.chunks = data.map(item => { 
                  return {
                    type: 'web',
                    source: item.link,
                    text: item.content
                  }
                 }).concat(splitTextModel.chunks);

                webCaptureConfirmLoading.value = false;
                webCaptureVisible.value = false;
            })
            .catch((err) => {
                console.log(err);
            });
    }

    watch(webCaptureVisible, (visible) => {
      if (!visible) {
        webCaptureLink.value = ''
      }
    })

    return {
      ...toRefs(state),
      loginCallback,
      changeTeamPopoverVisible,
      addTeamSuccess,
      handleTableChange,
      onSubmitWiki,
      showWikiSetting,
      settingValidateInfos,
      settingFormRef,
      onSettingSubmit,
      wikiFormRef,
      wikiValidateInfos,

      onCateClick,
      editCate,
      deleteCate,
      columns,
      getWikiData,
      removeKeywords,
      onDeleteData,
      onTabChange,

      modalTitle,
      modalHandleOk,
      onEditClick,
      downloadFile,
      splitTextModel,
      baseUrl,
      splitTextUploadChange,
      importCsvBeforeUpload,
      importCsvUploadChange,
      modalVisible,
      onPageChange,
      webCaptureVisible,
      webCaptureLink,
      onWebCaptureConfirm,
      webCaptureConfirmLoading
    };
  },
});
</script>

<style lang="less" scoped>
.wiki-list {
  width: 100%;
  height: 100%;
  padding: 20px;

  .content {
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: space-between;

    .left {
      width: 260px;
      height: 100%;
      background-color: #fff;
      padding: 10px 20px;
      border-radius: 4px;

      .cate-list {
        width: 100%;
        height: calc(100% - 52px);
        overflow: hidden auto;
        margin: 10px 0;

        .cate-list-item {
          padding: 8px 0 8px 10px;
          margin-top: 5px;
          border-radius: 4px;
          cursor: pointer;
          display: flex;
          justify-content: space-between;
          align-items: center;
        }

        .cate-list-item-current {
          background-color: #f7f0ff;
        }
      }
    }

    .right {
      width: calc(100% - 280px);
      height: 100%;
      background-color: #fff;
      padding: 10px 20px;
      border-radius: 4px;
      overflow: hidden auto;

      :deep(.ant-tabs-nav-container) {
        height: 36px;
      }
      :deep(.ant-tabs-tab) {
        width: 80px;
        text-align: center;
        height: 36px;
        line-height: 36px;
      }
      :deep(.ant-tabs-tab-active) {
        background-color: #f7f0ff;
      }

      .table-wrap {
        margin-top: 16px;
        min-height: 300px;
        max-height: calc(100% - 240px);
        overflow: hidden auto;
      }

      .pagination-wrap {
        display: flex;
        justify-content: center;
        align-items: center;
        padding: 20px 0;
      }
    }
  }
}
</style>

<style lang="less">
  .wiki-modal-warp .ant-tabs-bar {
    margin: 0px;
    border-bottom: none;
  }
</style>
